package com.edu.dsai.handler;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.collection.CollUtil;
import com.edu.dsai.constants.ResultConstants;
import com.edu.dsai.utils.R;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        List<String> errors = new ArrayList<>();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for (ObjectError error : allErrors) {
            errors.add(error.getDefaultMessage());
        }
        String errMsg = CollUtil.join(errors, ",");
        // 然后提取错误提示信息进行返回
        return R.failed(errMsg);
    }

    @ExceptionHandler(UserFriendlyException.class)
    public R UserFriendlyException(UserFriendlyException e) {
        e.printStackTrace();
        return R.failed(e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public R NotLoginException(NotLoginException e) {
        e.printStackTrace();
        return R.failed(ResultConstants.NOT_LOGIN_EXCEPTION);
    }

    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
        e.printStackTrace();
        return R.failed(e.getMessage());
    }
}
